package com.yyds.yygh.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mysql.jdbc.StringUtils;
import com.yyds.yygh.common.exception.YyghException;
import com.yyds.yygh.common.helper.JwtHelper;
import com.yyds.yygh.common.result.ResultStatus;
import com.yyds.yygh.enums.AuthStatusEnum;
import com.yyds.yygh.model.user.Patient;
import com.yyds.yygh.model.user.UserInfo;
import com.yyds.yygh.user.mapper.PatientMapper;
import com.yyds.yygh.user.mapper.UserInfoMapper;
import com.yyds.yygh.user.service.PatientService;
import com.yyds.yygh.user.service.UserInfoService;
import com.yyds.yygh.vo.user.LoginVo;
import com.yyds.yygh.vo.user.UserAuthVo;
import com.yyds.yygh.vo.user.UserInfoQueryVo;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper,UserInfo> implements UserInfoService {
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private PatientService patientService;

    @Override
    public Map<String, Object> login(LoginVo loginVo) {
        //获取手机号和验证码
        String phone = loginVo.getPhone();
        String loginCode = loginVo.getCode();
        //判断手机号或者验证码是否为空
        if (StringUtils.isNullOrEmpty(phone) || StringUtils.isNullOrEmpty(loginCode)){
            throw new YyghException(ResultStatus.PARAM_ERROR);
        }

        //TODO 校验验证码
        String code = redisTemplate.opsForValue().get(phone);
        if (StringUtils.isNullOrEmpty(code)){
            throw new YyghException(ResultStatus.CODE_ERROR);
        }
        if (!loginCode.equals(code)){
            throw new YyghException(ResultStatus.CODE_ERROR);
        }
//
//        //根据手机号判断用户是否存在
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone",phone);
        UserInfo userInfo = userInfoMapper.selectOne(queryWrapper);
        //判断用户是否存在
        if (userInfo == null){
            //如果不存在就注册
            userInfo = new UserInfo();
            userInfo.setName("");
            userInfo.setPhone(phone);
            userInfo.setStatus(1);
            this.save(userInfo);
        }
        //如果用户存在则判断状态是否正常
        if (userInfo.getStatus() == 0){
            throw new YyghException(ResultStatus.LOGIN_DISABLED_ERROR);
        }
        //返回用户的名字
        if (StringUtils.isNullOrEmpty(userInfo.getName())){
            userInfo.setName(userInfo.getNickName());
        }
        if (StringUtils.isNullOrEmpty(userInfo.getName())){
            userInfo.setName(userInfo.getPhone());
        }
        //创建最终返回的map集合
        Map<String, Object> map = new HashMap<>();
        map.put("name",userInfo.getName());
        //生成token
        String token = JwtHelper.createToken(userInfo.getId(), userInfo.getName());
        map.put("token",token);
        return map;
    }

    @Override
    public void userAuth(Long userId, UserAuthVo userAuthVo) {
        //根据Id查询用户信息
        UserInfo userInfo = baseMapper.selectById(userId);
        //将VO的信息封装到userInfo中
        userInfo.setName(userAuthVo.getName());
        userInfo.setCertificatesNo(userAuthVo.getCertificatesNo());
        userInfo.setCertificatesType(userAuthVo.getCertificatesType());
        userInfo.setCertificatesUrl(userAuthVo.getCertificatesUrl());
        userInfo.setAuthStatus(AuthStatusEnum.AUTH_RUN.getStatus());
        //执行更新
        baseMapper.updateById(userInfo);
    }

    //用户列表（条件查询带分页）
    @Override
    public IPage<UserInfo> selectPage(Page<UserInfo> pageParam, UserInfoQueryVo userInfoQueryVo) {
        //UserInfoQueryVo获取条件值
        String name = userInfoQueryVo.getKeyword(); //用户名称关键字
        Integer status = userInfoQueryVo.getStatus();//用户状态
        Integer authStatus = userInfoQueryVo.getAuthStatus(); //认证状态
        String createTimeBegin = userInfoQueryVo.getCreateTimeBegin(); //开始时间
        String createTimeEnd = userInfoQueryVo.getCreateTimeEnd(); //结束时间
        //对条件值进行非空判断
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        if(!StringUtils.isNullOrEmpty(name)) {
            wrapper.like("name",name);
        }
        if(status!=null) {
            wrapper.eq("status",status);
        }
        if(authStatus!=null) {
            wrapper.eq("auth_status",authStatus);
        }
        if(!StringUtils.isNullOrEmpty(createTimeBegin)) {
            wrapper.ge("create_time",createTimeBegin);
        }
        if(!StringUtils.isNullOrEmpty(createTimeEnd)) {
            wrapper.le("create_time",createTimeEnd);
        }
        //调用mapper的方法
        IPage<UserInfo> pages = baseMapper.selectPage(pageParam, wrapper);
        //编号变成对应值封装
        List<UserInfo> userInfoList = pages.getRecords();
        for (UserInfo userInfo : userInfoList) {
            userInfo = this.packageUserInfo(userInfo);
        }
        return pages;
    }

    @Override
    public void lock(Long id, Integer status) {
        if (status.intValue()==0 || status.intValue() ==1){
            UserInfo userInfo = userInfoMapper.selectById(id);
            userInfo.setStatus(status);
            userInfoMapper.updateById(userInfo);
        }
    }

    @Override
    public Map<String, Object> show(Long userId) {
        Map<String, Object> map = new HashMap<>();
        UserInfo userInfo = userInfoMapper.selectById(userId);
        userInfo = this.packageUserInfo(userInfo);
        map.put("userInfo",userInfo);
        List<Patient> patients = patientService.findAllByUserId(userId);
        map.put("patientList",patients);
        return map;
    }

    @Override
    public void approval(Long id, Integer authStatus) {
        if (authStatus.intValue()==2||authStatus.intValue()==-1){
            UserInfo userInfo = userInfoMapper.selectById(id);
            userInfo.setAuthStatus(authStatus);
            userInfoMapper.updateById(userInfo);
        }
    }

    //编号变成对应值封装
    private UserInfo packageUserInfo(UserInfo userInfo) {
        //处理认证状态编码
        userInfo.getParam().put("authStatusString",AuthStatusEnum.getStatusNameByStatus(userInfo.getAuthStatus()));
        //处理用户状态 0  1
        String statusString = userInfo.getStatus().intValue()==0 ?"锁定" : "正常";
        userInfo.getParam().put("statusString",statusString);
        return userInfo;
    }

}
